package wakeup.server.tcpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import wakeup.server.persistence.TrackDAO;

public class TcpServer extends Thread {
	
	private ServerSocket server;
	private final int port = 22255;
	private boolean running = true;
	TrackDAO trackDAO;
	
    private final Logger logger = Logger.getLogger("logger");
	
	
	public TcpServer() throws IOException {
		this.server = new ServerSocket(this.port);
		logger.log(Level.INFO, "Création du serveur TCP");
		
		trackDAO = new TrackDAO();	
	}
	
	@Override
    public void run() {
		
		logger.log(Level.INFO, "Attente de connexion d'un client");
	
		while (this.running) {
			try {
				// Attente de connexion au socket puis cr�ation des threads.
				final Socket socket = this.server.accept();
				logger.log(Level.INFO, "Connexion d'un nouveau client");
				ClientHandler handler = new ClientHandler(socket, trackDAO);
				new Thread(handler).start();
                
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				// Solution mi sale pour stoper le thread
				Thread.currentThread().interrupt(); 
                break;
			} 
		}
		
		logger.log(Level.INFO, "Fin du serveur TCP");
	}
	
	public boolean isRunning() {
		return this.running;
	}
	
	public void stopServer() throws IOException {
		logger.log(Level.INFO, "Shutdown du serveur TCP");
		this.running = false;
		this.server.close();
	}
	
}
